<template>
  <div class="facility-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">设备管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>
        新增设备
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="设备编码">
            <el-input v-model="searchForm.facilityCode" placeholder="请输入设备编码" clearable />
          </el-form-item>
          <el-form-item label="设备名称">
            <el-input v-model="searchForm.facilityName" placeholder="请输入设备名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchFacilities" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 设备列表 -->
    <div class="table-section">
      <el-card>
        <el-table 
          :data="facilityList" 
          v-loading="loading"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="faciltyCode" label="设备编码" width="150" />
          <el-table-column prop="faciltyName" label="设备名称" width="200" />
          <el-table-column prop="facilyMessage" label="设备描述" min-width="250" />
          <el-table-column prop="addProp" label="创建人" width="120" />
          <el-table-column prop="addTime" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.addTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updProp" label="修改人" width="120" />
          <el-table-column prop="updTime" label="修改时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.updTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="editFacility(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button link type="danger" @click="deleteFacility(scope.row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 新增/编辑设备对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="facilityFormRef"
        :model="facilityForm" 
        :rules="facilityRules" 
        label-width="100px"
      >
        <el-form-item label="设备编码" prop="faciltyCode">
          <el-input 
            v-model="facilityForm.faciltyCode" 
            placeholder="请输入设备编码"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="设备名称" prop="faciltyName">
          <el-input 
            v-model="facilityForm.faciltyName" 
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="设备描述" prop="facilyMessage">
          <el-input 
            v-model="facilityForm.facilyMessage" 
            type="textarea" 
            :rows="4"
            placeholder="请输入设备描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import Maxios from '@/Http/MesHelp'
import moment from 'moment'
import router from '@/router'

// 接口定义
interface FacilityModel {
  id: number
  faciltyCode: string
  faciltyName: string
  facilyMessage: string
  addProp: string
  addTime: string
  updProp?: string
  updTime?: string
  isDel: boolean
}

interface SearchForm {
  facilityCode: string
  facilityName: string
}

interface FacilityForm {
  id?: number
  faciltyCode: string
  faciltyName: string
  facilyMessage: string
  addProp?: string
  updProp?: string
}

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const facilityList = ref<FacilityModel[]>([])
const facilityFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive<SearchForm>({
  facilityCode: '',
  facilityName: ''
})

// 设备表单
const facilityForm = reactive<FacilityForm>({
  faciltyCode: '',
  faciltyName: '',
  facilyMessage: ''
})

// 表单验证规则
const facilityRules: FormRules = {
  faciltyCode: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
    { min: 2, max: 50, message: '设备编码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  faciltyName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 100, message: '设备名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  facilyMessage: [
    { max: 500, message: '设备描述不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑设备' : '新增设备')

// 方法
const formatDate = (date: string | null) => {
  if (!date) return '-'
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取设备列表
const getFacilityList = async () => {
  loading.value = true
  try {
    const response = await Maxios.post('/api/Facilty/FaciltyGet')
    if (response.data.code === 200) {
      facilityList.value = response.data.data || []
      ElMessage.success('获取设备列表成功')
    } else {
      ElMessage.error(response.data.message || '获取设备列表失败')
    }
  } catch (error: any) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索设备
const searchFacilities = async () => {
  loading.value = true
  try {
    const params = {
      facilityCode: searchForm.facilityCode || undefined,
      facilityName: searchForm.facilityName || undefined
    }
    
    const response = await Maxios.post('/api/Facilty/FaciltyGet', null, { params })
    if (response.data.code === 200) {
      let filteredList = response.data.data || []
      
      // 前端过滤（如果后端不支持条件查询）
      if (searchForm.facilityCode) {
        filteredList = filteredList.filter((item: FacilityModel) => 
          item.faciltyCode.toLowerCase().includes(searchForm.facilityCode.toLowerCase())
        )
      }
      if (searchForm.facilityName) {
        filteredList = filteredList.filter((item: FacilityModel) => 
          item.faciltyName.toLowerCase().includes(searchForm.facilityName.toLowerCase())
        )
      }
      
      facilityList.value = filteredList
      ElMessage.success(`查询到 ${filteredList.length} 条记录`)
    } else {
      ElMessage.error(response.data.message || '查询失败')
    }
  } catch (error: any) {
    console.error('查询设备失败:', error)
    ElMessage.error('查询设备失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.facilityCode = ''
  searchForm.facilityName = ''
  getFacilityList()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑设备
const editFacility = (row: FacilityModel) => {
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  facilityForm.id = row.id
  facilityForm.faciltyCode = row.faciltyCode
  facilityForm.faciltyName = row.faciltyName
  facilityForm.facilyMessage = row.facilyMessage
  facilityForm.updProp = '当前用户' // 这里应该从用户信息中获取
}

// 重置表单
const resetForm = () => {
  facilityForm.id = undefined
  facilityForm.faciltyCode = ''
  facilityForm.faciltyName = ''
  facilityForm.facilyMessage = ''
  facilityForm.addProp = '当前用户' // 这里应该从用户信息中获取
  facilityForm.updProp = ''
  
  // 清除验证
  facilityFormRef.value?.clearValidate()
}

// 提交表单
const submitForm = async () => {
  if (!facilityFormRef.value) return
  
  try {
    await facilityFormRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await updateFacility()
    } else {
      await addFacility()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 添加设备
const addFacility = async () => {
  try {
    const requestData = {
      faciltyCode: facilityForm.faciltyCode,
      faciltyName: facilityForm.faciltyName,
      facilyMessage: facilityForm.facilyMessage,
      addProp: localStorage.getItem("userNickname")
    }
    
    const response = await Maxios.post('/api/Facilty/FaciltyAdd', requestData)
    if (response.data.code === 200) {
      ElMessage.success('设备添加成功')
      dialogVisible.value = false
      getFacilityList()
    } else {
      ElMessage.error(response.data.message || '设备添加失败')
    }
  } catch (error: any) {
    console.error('添加设备失败:', error)
    ElMessage.error('设备添加失败')
  }
}

// 更新设备
const updateFacility = async () => {
  try {
    const requestData = {
      id: facilityForm.id,
      faciltyCode: facilityForm.faciltyCode,
      faciltyName: facilityForm.faciltyName,
      facilyMessage: facilityForm.facilyMessage,
      updProp: localStorage.getItem("userNickname")
    }
    
    const response = await Maxios.post('/api/Facilty/FaciltyUpdate', requestData)
    if (response.data.code === 200) {
      ElMessage.success('设备更新成功')
      dialogVisible.value = false
      getFacilityList()
    } else {
      ElMessage.error(response.data.message || '设备更新失败')
    }
  } catch (error: any) {
    console.error('更新设备失败:', error)
    ElMessage.error('设备更新失败')
  }
}

// 删除设备
const deleteFacility = async (row: FacilityModel) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除设备"${row.faciltyName}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    loading.value = true
    const response = await Maxios.post('/api/Facilty/FaciltyDel', { id: row.id })
    
    if (response.data.code === 200) {
      ElMessage.success('设备删除成功')
      getFacilityList()
    } else {
      ElMessage.error(response.data.message || '设备删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除设备失败:', error)
      ElMessage.error('设备删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  getFacilityList()
})
</script>

<style scoped>
.facility-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-section {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .facility-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>
